﻿using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
using Ninject.Web.Mvc;
using System.Reflection;
using MVCThemes;
using P7DC.Web.Common.IoC;
using P7DC.Web.Common.Injection;

namespace P7DC.Web
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : NinjectHttpApplication
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

		/// <summary>
		/// Make conteoller depencies
		/// </summary>
		/// <returns>Kernel</returns>
		protected override IKernel CreateKernel()
		{
			var kernel = new StandardKernel();
			kernel.Load(Assembly.GetExecutingAssembly());
			DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
			return kernel;
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
			// Theme
			routes.IgnoreRoute("themes/{*pathInfo}");
			routes.IgnoreRoute("content/{*pathInfo}");

			// Admin
			routes.MapRoute(
				"ElmahLog", // Route name
				"Admin/Log/{type}", // URL with parameters
				new { controller = MVC.Elmah.Name, action = MVC.Elmah.ActionNames.Index, type = UrlParameter.Optional } // Parameter defaults
			);

			// Default
			routes.MapRoute(
				"Default", // Route name
				"{controller}/{action}/{id}", // URL with parameters
				new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index, id = UrlParameter.Optional } // Parameter defaults
			);
		}

		protected override void OnApplicationStarted()
		{
			base.OnApplicationStarted();

			// Init IOC
			ObjectFactoryHelper.InitRegistry();

			// Theme
			ViewEngines.Engines.Clear();
			ViewEngines.Engines.Add(new ThemeViewEngine());

			AreaRegistration.RegisterAllAreas();
			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);
		}
	}
}